package client

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"

	"minio.com/minio-sdk/util"
)

type Client struct {
	cli    *http.Client
	logger *log.Logger
}

var SERVER_IPs = []string{"127.0.0.1:9000/", "127.0.0.1:9000/", "127.0.0.1:9000/"}

// init
func (c *Client) Init() {
	// set log
	logFile, err := os.OpenFile(util.LoggerFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		fmt.Println("open log file failed, err:", err)
		return
	}
	c.logger = log.New(logFile, "[HTTP client] -> ", log.Lshortfile|log.Ldate|log.Ltime)

	// set HTTP client
	tr := &http.Transport{}
	c.cli = &http.Client{Transport: tr}
}

func (c *Client) GetObject(id int, bucket string, oid string) ([]byte, error) {
	url := SERVER_IPs[id] + "get?bucket=" + bucket + "&oid=" + oid
	resp, err := c.cli.Get(url)
	if err != nil {
		c.logger.Println("minio get obj err:", err)
		return nil, err
	}
	defer resp.Body.Close()
	ret, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		c.logger.Println("response read err:", err)
		return nil, err
	}
	return ret, nil
}
